<template>
  <div class="system-menu-container">
		<div class="system-user-search mb15">
			<el-form :model="param" :inline="true" ref="queryFormRef" @keyup.enter.native="loadList" label-width="120px">
				<el-row>
					<el-col :span="6">
						<el-form-item prop="startUseName" label="发起人">
							<el-input v-model="param.startUseName" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item prop="processName" label="流程名称">
							<el-input v-model="param.processName" clearable placeholder="暂不支持模糊查询"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item prop="oper_time_start" label="起始时间">
							<el-date-picker v-model="param.oper_time_start" type="date" placeholder="请选择日期" clearable value-format="YYYY-MM-DD" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-button type="primary" class="ml7" @click="loadList">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6">
						<el-form-item prop="description" label="流程摘要">
							<el-input v-model="param.description" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item prop="processState" label="流程状态">
							<DicSelect v-model="param.processState" placeholder="请选择" dicCode="LCZT" style="width:100%"></DicSelect>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item prop="oper_time_end" label="结束时间">
							<el-date-picker v-model="param.oper_time_end" type="date" placeholder="请选择日期" clearable value-format="YYYY-MM-DD" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<el-table :data="dataList" border v-loading="listLoading" style="width: 100%;">
			<el-table-column prop="processName" label="流程名称" width="150"></el-table-column>
			<el-table-column prop="startUserName" label="发起人" width="80"></el-table-column>
			<el-table-column prop="startTime" width="135" label="发起时间" :formatter="formatDate"></el-table-column>
			<el-table-column prop="endTime" width="135" label="结束时间" :formatter="formatDate"></el-table-column>
			<el-table-column prop="processState" column-key="LCZT"  width="80" :formatter="formatStatus" label="流程状态"></el-table-column>
			<el-table-column prop="nodeName" label="当前节点" width="150"></el-table-column>
			<el-table-column prop="curUserName" label="当前处理人" width="150"></el-table-column>
			<el-table-column prop="description" label="流程摘要"></el-table-column>
			<el-table-column prop="deleteReason" width="160" label="强制终止原因"></el-table-column>
			<el-table-column  width="150" label="操作">
				<template  #default="scope">
					<el-button type="primary" link @click="showProcess(scope.row.processDifinationId, scope.row.id)" >跟踪</el-button>
					<el-button type="primary" link v-if="scope.row.processState == '0'" @click="setAssignee(scope.row.processDifinationId, scope.row.id)" >指派</el-button>
					<el-button type="primary" link v-if="scope.row.processState == '0'" @click="tip(scope.row.id,scope.row.processState)" >终止</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			@size-change="onHandleSizeChange"
			@current-change="onHandleCurrentChange"
			:pager-count="5"
			:page-sizes="[10, 50, 200]"
			v-model:current-page="param.page"
			background
			v-model:page-size="param.limit"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total" small>
		</el-pagination>
		<el-dialog title="流程跟踪" v-model="dialogVisible" width="80%" class="customDialog">
			<div class="tabsBackground">
				<iframe id="show-iframe2"  frameborder=0 name="showHere2" scrolling=auto :src="src2" width="100%" height="700px"></iframe>
			</div>
		</el-dialog>
		<el-dialog title="指派处理人" v-model="assigneeVisible" width="60%" class="customDialog" :close-on-click-modal="false">
			<el-form :model="userParam" :inline="true" ref="userQueryFormRef" @keyup.enter.native="loadUserList" label-width="120px">
				<el-form-item prop="orgName" label="部门">
					<el-input v-model="userParam.orgName" clearable></el-input>
				</el-form-item>
				<el-form-item prop="staffName" label="姓名">
					<el-input v-model="userParam.staffName" clearable></el-input>
				</el-form-item>
				<el-button type="primary" class="ml7" @click="loadUserList">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button type="primary" class="ml10" @click="reSetUserQueryForm(userQueryFormRef)">
					<el-icon>
						<ele-Refresh />
					</el-icon>
					重置
				</el-button>
			</el-form>
			<el-table :data="userList" border v-loading="userListLoading" @selection-change="selectionChangeHandle" style="width: 100%;">
				<el-table-column prop="id" type="selection" width="50"> </el-table-column>
				<el-table-column prop="orgName" label="部门" ></el-table-column>
				<el-table-column prop="staffName" label="姓名" ></el-table-column>
			</el-table>
			<el-pagination
				@size-change="onUserHandleSizeChange"
				@current-change="onUserHandleCurrentChange"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="userParam.page"
				background
				v-model:page-size="userParam.limit"
				layout="total, sizes, prev, pager, next, jumper"
				:total="userTotal">
			</el-pagination>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose()">取消</el-button>
					<el-button type="primary" @click="selectSubmit()">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, defineComponent } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import {workflowApi} from '/@/api/workflowapi'
import { getCodeList } from '/@/utils/cacheDict'
import {systemApi} from '/@/api/systemapi'
export default defineComponent({
	setup () {
		const dataFormRef = ref<FormInstance>()
		const queryFormRef = ref<FormInstance>()
		const userQueryFormRef = ref<FormInstance>()
		const state = reactive({
			isShow: false,
			listLoading: false,
			dataList: [],
			total: 0,
			userTotal: 0,
			totalSelect: 0,
			param: {
				page: 1,
				limit: 10,
				startUseName:'',
				processName:'',
				oper_time_start:null,
				oper_time_end:null,
				processState:"" ,
				description:""
			},
			dataListSelections: [],
			dialogVisible: false,
			dataDictionaryList: {},
			src2: '',
			assigneeVisible: false,
			userListLoading: false,
			userParam: {
				page: 1,
				limit: 10,
				orgName:'',
				staffName:''
			},
			userList: [],
			checkProcessId: ''
		})

		// 页面加载时
		onMounted(() => {
			// 数据字典
			getCodeList(state, ['LCZT'])
			// 列表查询
			loadList()
		})

		//查询
		const loadList = () => {
			state.listLoading = true
			workflowApi().querygetProcessList(state.param).then(data => {
				if (data && data.code === 0) {
					state.dataList = data.page.list
					state.total = data.page.totalCount
				} else {
					state.dataList = []
					state.total = 0
				}
			}).catch(() => {
			}).finally(() => {
				state.listLoading = false
			})
		}
		//重置
		const reSetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.param.page = 1
			loadList()
		}

		// 分页改变
		const onHandleSizeChange = (val: number) => {
			state.param.limit = val;
			loadList()
		}
		// 分页改变
		const onHandleCurrentChange = (val: number) => {
			state.param.page = val;
			loadList()
		}

		const tip = (id: string, state: string) => {
			if(state!='0') {
				ElMessage.error('流程已结束，无需操作！')
				return
			}
			ElMessageBox.prompt('请输入终止原因', '终止', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(({ value }) => {
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				workflowApi().deleteProcess({
					'processid': id,
					'deleteReason': value
				}).then((data) => {
					if (data.code === 0) {
						ElMessage.success('成功终止')
						loadList()
					}else{
						ElMessage.error("终止失败！")
					}
				}).catch(() =>{
					ElMessage.error("终止失败！")
				}).finally(() => {
					loading.close()
				})
			}).catch(() => {
			})
		}

		const showProcess = (processDifinationId: string, processId: string) => {
          state.dialogVisible = true
          state.src2 = import.meta.env.VITE_API_URL + '/activiti/diagram-viewer/index.html?processDefinitionId=' + processDifinationId + '&processInstanceId=' + processId
        }

		const formatStatus = (row:any, column:any, cellValue:any, index:number) => {
			if(Object.keys(state.dataDictionaryList).length>0){
				if (cellValue) {
					return state.dataDictionaryList[column.columnKey][cellValue];
				}
			}
		}
		const setAssignee = (processDifinationId: string, processId: string) =>{
			state.dataListSelections = []
			state.checkProcessId = processId
			state.assigneeVisible = true
			loadUserList()
		}
		const selectionChangeHandle = (val: any) => {
			state.dataListSelections = val
		}
		// 分页改变
		const onUserHandleSizeChange = (val: number) => {
			state.dataListSelections = []
			state.userParam.limit = val;
			loadUserList()
		}
		// 分页改变
		const onUserHandleCurrentChange = (val: number) => {
			state.dataListSelections = []
			state.userParam.page = val;
			loadUserList()
		}
		//加载用户
		const loadUserList = () =>{
			state.userListLoading = true
			systemApi().queryUserSkiving(state.userParam).then(data => {
				if (data && data.code === 0) {
					state.userList = data.page.list
					state.userTotal = data.page.totalCount
				} else {
					state.userList = []
					state.userTotal = 0
				}
			}).catch(() => {
			}).finally(() => {
				state.userListLoading = false
			})
		}
		//重置
		const reSetUserQueryForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.userParam.page = 1
			loadUserList()
		}
		//取消选人
		const handleClose = () => {
			state.assigneeVisible = false
			state.dataListSelections = []
			loadUserList()
		}
		//指派给选择的人
		const selectSubmit = () => {
			if(state.dataListSelections.length == 0){
				ElMessage.warning('请选择需要指派的人')
				return
			}
			let ids = state.dataListSelections.map(item => {
				return item.id
			})
			const loading = ElLoading.service({
				lock: true,
				text: '处理中',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			workflowApi().addAssignee(state.checkProcessId, ids).then((data) => {
				if (data && data.code === 0) {
					ElMessage.success('指派处理人成功')
					state.assigneeVisible = false
					state.dataListSelections = []
					loadUserList()
				} else {
					ElMessage.error(data.msg)
				}
			}).catch(() => {
				ElMessage.error('指派处理人失败！')
			}).finally(() => {
				loading.close()
			})
		}
		return {
			loadList,
			reSetForm,
			onHandleSizeChange,
			onHandleCurrentChange,
			showProcess,
			dataFormRef,
			queryFormRef,
			formatStatus,
			tip,
			selectionChangeHandle,
			userQueryFormRef,
			onUserHandleSizeChange,
			onUserHandleCurrentChange,
			loadUserList,
			reSetUserQueryForm,
			setAssignee,
			handleClose,
			selectSubmit,
			...toRefs(state),
		}
	}
})
</script>

<style>

</style>